<?php
namespace app\index\controller;
use app\model\Product as ProductModel;
use think\Db;


class Product extends Base
{
    public function __construct(){
        $model = new ProductModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '产品';

        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info
        ]);
    }

    public function detail($id){
        $data = ProductModel::where('id',$id)->find();
        if (!empty($data)) {
            ProductModel::where('id',$id)->inc('view_num')->update();

            $data['category_name'] = Db::name('category')->where('id',$data['category_id'])->value('name');
            if (!empty($data['image'])) {
                $data['image'] = explode(",",$data['image']);
            }else{
                $data['image'] = [];   
            }
            if (!empty($data['max_description'])) {
                $data['max_description'] = explode("\r\n",$data['max_description']);
            }else{
                $data['max_description'] = [];   
            }
        }
        
        return view('detail', [
            'data'=>$data
        ]);
    }

    public function buy(){
        return view('buy', [
        ]);
    }

    public function index(){
        $model = $this->model;
        $map_params = [
            ['key'=>'category_id','type'=>'=']
        ];
        $map = getSearchParam($map_params);
        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>input('page_size',12)
        ];
        $list = $model->where($map)->order('ctime','desc')->paginate($page_param);
        $page = $list->render();
        $page = indexPage($page);
        // $page = preg_replace(["/<div>.*<\/div>/","(<li[^<>]*>)"],'',$page);
        // $page = str_replace(['<ul class="pagination">','</li>','</ul>'],'',$page);

        $list = $list->toarray();
        foreach ($list['data'] as $k => $vo) {
            if (!empty($vo['image'])) {
                $list['data'][$k]['image'] = explode(",",$vo['image']);
            }else{
                $list['data'][$k]['image'] = [];   
            }
        }
        
        return view('index', [
            'list'=>$list,
            'page'=>$page
        ]);
    }


    
}
